<template>
  <div class="encryption-status" v-if="showStatus">
    <el-tooltip :content="tooltipContent" placement="top">
      <div class="status-indicator" @click="toggleEncryption">
        <i :class="['el-icon', encrypted ? 'el-icon-lock' : 'el-icon-unlock']"></i>
        <span>{{ encrypted ? '已加密' : '未加密' }}</span>
      </div>
    </el-tooltip>
    
    <!-- 添加连接测试按钮 -->
    <div class="connection-test" @click="testConnection">
      <i :class="['el-icon', connected ? 'el-icon-connection' : 'el-icon-warning']"></i>
      <span>{{ connected ? '已连接' : '未连接' }}</span>
    </div>
    
    <!-- 添加重新初始化加密按钮 -->
    <div class="reinit-encryption" @click="reinitEncryption">
      <i class="el-icon-refresh"></i>
      <span>重新初始化加密</span>
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue'
import { useWebsocketStore } from '@/stores/modules/websocket'
import { getEncryptionStatusApi } from '@/api/other'
import { ElMessage } from 'element-plus'

const websocketStore = useWebsocketStore()

// 是否显示状态指示器（仅在开发环境显示）
const showStatus = import.meta.env.DEV

// 服务器端加密状态
const serverEncryption = ref({
  enabled: false,
  user_encrypted: false
})

// 连接状态
const connected = ref(false)

// 计算属性：获取加密状态
const encrypted = computed(() => {
  // 客户端和服务器端都启用加密，且已建立加密通道
  const clientEnabled = websocketStore.encrypted;
  const clientEncrypted = websocketStore.socket?.isEncrypted || false;
  const serverEnabled = serverEncryption.value.enabled;
  const serverEncrypted = serverEncryption.value.user_encrypted;
  
  console.log('🔒 加密状态检查:', {
    客户端启用: clientEnabled,
    客户端已加密: clientEncrypted,
    服务器启用: serverEnabled,
    服务器已加密: serverEncrypted
  });
  
  return clientEnabled && 
         serverEnabled && 
         (clientEncrypted || serverEncrypted);
})

// 提示内容
const tooltipContent = computed(() => {
  if (encrypted.value) {
    return '通信已加密，点击查看详情'
  } else if (websocketStore.encrypted && !serverEncryption.value.enabled) {
    return '客户端已启用加密，但服务器未启用'
  } else if (!websocketStore.encrypted && serverEncryption.value.enabled) {
    return '服务器已启用加密，但客户端未启用'
  } else if (websocketStore.encrypted && !websocketStore.socket?.isEncrypted) {
    return '加密已启用但未初始化完成，点击查看详情'
  } else {
    return '通信未加密，点击查看详情'
  }
})

// 获取服务器端加密状态
const getServerEncryptionStatus = async () => {
  try {
    const res = await getEncryptionStatusApi()
    if (res?.code === 200 && res.data) {
      serverEncryption.value = res.data
      console.log('服务器加密状态:', serverEncryption.value)
    }
  } catch (error) {
    console.error('获取服务器加密状态失败:', error)
  }
}

// 切换加密状态或显示详情
const toggleEncryption = () => {
  if (import.meta.env.DEV) {
    // 显示详细信息
    console.log('加密状态详情:', {
      客户端: {
        已启用: websocketStore.encrypted,
        已连接: !!websocketStore.socket,
        已加密: websocketStore.socket?.isEncrypted || false
      },
      服务器: serverEncryption.value
    })
    
    // 刷新服务器状态
    getServerEncryptionStatus()
  }
}

// 重新初始化加密过程
const reinitEncryption = () => {
  if (!websocketStore.socket) {
    ElMessage.warning('WebSocket未初始化，正在尝试初始化...')
    websocketStore.init()
    setTimeout(() => {
      if (websocketStore.socket && websocketStore.socket.status === 1) {
        // 手动调用initEncryption方法
        if (websocketStore.socket.initEncryption) {
          ElMessage.info('正在重新初始化加密过程...')
          websocketStore.socket.initEncryption()
        }
      }
    }, 2000)
    return
  }
  
  if (websocketStore.socket.status !== 1) {
    ElMessage.warning('WebSocket未连接，正在尝试重连...')
    websocketStore.socket.connect()
    setTimeout(() => {
      if (websocketStore.socket.status === 1) {
        // 手动调用initEncryption方法
        if (websocketStore.socket.initEncryption) {
          ElMessage.info('正在重新初始化加密过程...')
          websocketStore.socket.initEncryption()
        }
      }
    }, 2000)
    return
  }
  
  // WebSocket已连接，直接初始化加密
  if (websocketStore.socket.initEncryption) {
    ElMessage.info('正在重新初始化加密过程...')
    console.log('🔒 手动触发加密初始化')
    websocketStore.socket.initEncryption()
    
    // 检查加密状态
    setTimeout(() => {
      if (websocketStore.socket.isEncrypted) {
        ElMessage.success('加密初始化成功!')
      } else {
        ElMessage.warning('加密未完成，请检查控制台日志')
      }
    }, 3000)
  } else {
    ElMessage.error('WebSocket对象不支持加密初始化')
  }
}

// 测试WebSocket连接
const testConnection = () => {
  if (!websocketStore.socket) {
    ElMessage.warning('WebSocket未初始化，正在尝试初始化...')
    websocketStore.init()
    setTimeout(checkConnection, 2000)
    return
  }
  
  if (websocketStore.socket.status !== 1) {
    ElMessage.warning('WebSocket未连接，正在尝试重连...')
    websocketStore.socket.connect()
    setTimeout(checkConnection, 2000)
    return
  }
  
  // 发送测试消息
  try {
    websocketStore.send({ type: 0 }) // 发送心跳消息
    ElMessage.success('已发送测试消息，请查看控制台日志')
    connected.value = true
  } catch (error) {
    console.error('发送测试消息失败:', error)
    ElMessage.error('发送测试消息失败')
    connected.value = false
  }
}

// 检查连接状态
const checkConnection = () => {
  connected.value = websocketStore.socket && websocketStore.socket.status === 1
  
  if (connected.value) {
    ElMessage.success('WebSocket连接成功')
  } else {
    ElMessage.error('WebSocket连接失败')
  }
}

// 定期检查连接状态
const startConnectionCheck = () => {
  setInterval(() => {
    connected.value = websocketStore.socket && websocketStore.socket.status === 1
  }, 5000)
}

// 组件挂载时获取服务器加密状态
onMounted(() => {
  getServerEncryptionStatus()
  checkConnection()
  startConnectionCheck()
})
</script>

<style scoped>
.encryption-status {
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 1000;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.status-indicator, .connection-test, .reinit-encryption {
  display: flex;
  align-items: center;
  padding: 6px 12px;
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s;
}

.status-indicator:hover, .connection-test:hover, .reinit-encryption:hover {
  background-color: rgba(0, 0, 0, 0.8);
}

.status-indicator i, .connection-test i, .reinit-encryption i {
  margin-right: 5px;
}

.connection-test {
  background-color: rgba(0, 0, 0, 0.5);
}

.reinit-encryption {
  background-color: rgba(0, 0, 0, 0.4);
}
</style> 